<?php
/**
 * @author renjianhong
 * @date 2021-10-28
 */
namespace Modules\Order\Services\Api;

use App\Models\Area;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Modules\Order\Entities\BaseModel;
use Modules\Order\Entities\Order;
use Modules\Order\Entities\Cart;
use Modules\Order\Entities\GoodsCat;
use Modules\Order\Entities\GoodsCats;
use Modules\Order\Entities\Goods;
use Modules\Order\Entities\UserLevel;
use Modules\Order\Entities\User;
use Modules\Order\Entities\OrderDetail;
use Modules\Order\Entities\MallSetting;
use Modules\Order\Entities\Coupon;
use Modules\Order\Entities\ShareSetting;
use Modules\Order\Entities\UserCoupon;
use Modules\Order\Entities\ShareUser;
use Modules\Order\Entities\UserAddress;
use Modules\Order\Entities\PostageRules;
use Modules\Order\Entities\OfferPrice;
use Modules\Order\Entities\OrderRefund;
use Modules\Order\Entities\UserCapitalLog;
use Modules\Order\Entities\TerritorialLimitation;
use Modules\Order\Entities\FreeDeliveryRules;
use Modules\Order\Entities\ShareLog;
use Modules\Order\Validate\Api\OrderValidate;
use function Sodium\compare;
use Flex\Express\Express;

class OrderListServices extends BaseService
{

    /**
     * @var Request
     */
    private $request;

    /**
     * @var bool
     * @author tan bing
     */
    public bool $deletePass = false;

    /**
     * @param Request $request
     */
    public function __construct(Request $request)
    {
        $this->request = $request;
    }

    /**
     * 获取订单列表
     * @return $data
     */
    public function list()
    {
        $mall_setting = MallSetting::first();
        
        $limit = $this->request->input('limit',10);
        $page = $this->request->input('page',1);
        $status = $this->request->input('status',-1);
        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");

        $query = Order::where([
            ['is_recycle','=',0],
            ['is_delete','=',0],
            ['user_id','=',$user_id],
        ]);
        if ($status == -1) {//全部
            
        }
        if ($status == 0) {//待付款
            $query->where([
                ['order_status','=',0]
            ]);
        }
        if ($status == 1) {//待发货
            $query->where([
                ['order_status','=',1]
            ]);
        }
        if ($status == 2) {//待收货
            $query->where([
                ['order_status','=',2]
            ]);
        }
        if ($status == 3) {//已完成
            $query->whereIn('order_status', [3, 6]);
        }
        if ($status == 4) {//售后订单
            return $this->getRefundList($user_id,$limit,$page);
        }
        
        $count = $query->count();

        //求偏移量
        $offset = ($page-1)*$limit;
        /* @var Order[] $list */
        $list = $query->offset($offset)->limit($limit)->orderBy('created_at', 'DESC')->get()->toArray();
        $new_list = [];
        foreach ($list as $order) {
            $order_detail_list = OrderDetail::where([['order_id','=',$order['id']], ['is_delete' ,'=', 0]])->get()->toArray();
            $goods_list = [];
            foreach ($order_detail_list as $order_detail) {
                $goods_list[] = (object)[
                    'goods_id' => $order_detail['goods_id'],
                    'goods_pic' => $order_detail['goods_pic'],
                    'goods_name' => $order_detail['goods_name'],
                    'num' => $order_detail['goods_num'],
                    'price' => $order_detail['goods_price'],
                    'attr_list' => json_decode($order_detail['goods_attr']),
                ];
            }
            $qrcode = null;
            if ($order['mch_id']) {
                $mch = Mch::find($order['mch_id']);
                $mch = [
                    'id' => $mch->id,
                    'name' => $mch->name,
                    'logo' => $mch->logo,
                ];
            } else {
                $mch = [
                    'id' => 0,
                    'name' => '平台自营',
                    'logo' => '',
                ];
            }
            $overtime = strtotime($order['created_at'])+(($mall_setting->over_day * 60) * 60);
            
            $new_list[] = (object)[
                'order_id' => $order['id'],
                'order_no' => $order['order_no'],
                'addtime' => $order['created_at'],
                'overtime' => $overtime,
                'goods_list' => $goods_list,
                'total_price' => $order['total_price'],
                'pay_price' => $order['pay_price'],
                'order_status' => $order['order_status'],
                'apply_delete' => $order['apply_delete'],
                'is_offline' => $order['is_offline'],
                'qrcode' => $qrcode,
                'express' => $order['express'],
                'mch' => $mch,
                'pay_type' => $order['pay_type'],
            ];
        }
        $pay_type_list = $this->getPayment();

        $data = [
            'row_count' => $count,
            'list' => $new_list,
            'pay_type_list' => $pay_type_list
        ];
        return $data;
    }

    /**
     * 售后订单信息
     * @return $data
     */
    private function getRefundList($user_id, $limit, $page)
    {
        $where = [
            ['order_refund.user_id','=',$user_id],
            ['order_refund.is_delete','=',0],
            ['order.is_delete','=',0],
            ['order_detail.is_delete','=',0]
        ];
        $query = OrderRefund::where($where)
            ->leftJoin('order_detail', 'order_detail.id','=','order_refund.order_detail_id')
            ->leftJoin('order', 'order.id','=','order_refund.order_id');
            
        $count = $query->count();

        //求偏移量
        $offset = ($page-1)*$limit;
        
        $list = $query->select('order.id AS order_id','order.order_no','order_refund.id AS order_refund_id','order_detail.goods_id','order_detail.created_at','order_detail.goods_num','order_detail.goods_price as total_price','order_detail.goods_attr','order_refund.refund_price','order_refund.refund_type','order_refund.refund_status','order_refund.is_agree','order_refund.is_user_send')->offset($offset)->limit($limit)->orderBy('order_refund.created_at','DESC')->get()->toArray();
        $new_list = [];
        foreach ($list as $item) {
            $goods = Goods::find($item['goods_id']);
            if (!$goods) {
                continue;
            }
            $domain = BaseModel::getDomain();
            $new_list[] = (object)[
                'order_id' => intval($item['order_id']),
                'order_no' => $item['order_no'],
                'goods_list' => [(object)[
                    'goods_id' => intval($goods->id),
                    'goods_pic' => $domain.'/'.$goods->pic,
                    'goods_name' => $goods->name,
                    'num' => intval($item['goods_num']),
                    'price' => doubleval(sprintf('%.2f', $item['total_price'])),
                    'attr_list' => json_decode($item['goods_attr']),
                ]],
                'addtime' => $item['created_at'],
                'refund_price' => doubleval(sprintf('%.2f', $item['refund_price'])),
                'refund_type' => $item['refund_type'],
                'refund_status' => $item['refund_status'],
                'order_refund_id' => $item['order_refund_id'],
                'is_agree' => $item['is_agree'],
                'is_user_send' => $item['is_user_send'],
            ];
        }
        
        $data = [
            'row_count' => $count,
            'list' => $new_list,
        ];
        return $data;
    }

    /**
     * 订单取消
     * @return
     */
    public function revoke()
    {
        $user_id = $this->request->attributes->get('userId');
        $order_id = $this->request->input('order_id');
        $order = Order::where([
            ['user_id','=', $user_id],
            ['id' ,'=', $order_id],
            ['is_delete','=', 0],
        ])->whereIn('order_status',[0,1])->first();
        
        if (!$order) {
            throw new \Exception("订单不存在");
        }
        //已支付订单需要后台先审核
        if ($order->order_status == 1 && !$this->deletePass) {
            $order->apply_delete = 1;
            // TODO 发送消息通知
            if (!$order->save()) {
                throw new \Exception("取消失败，请稍后重试");
            }

            return "订单取消申请已提交，请等候管理员审核";
        }

        $order->order_status = 4;
        $order_detail_list = OrderDetail::where([['order_id' ,'=', $order->id], ['is_delete' ,'=', 0]])->get();

        DB::beginTransaction();

        //库存恢复
        foreach ($order_detail_list as $order_detail) {
            $goods = Goods::find($order_detail->goods_id);
            $attr_id_list = [];
            foreach (json_decode($order_detail->goods_attr) as $item) {
                array_push($attr_id_list, $item->attr_id);
            }
            $goods->numAdd($attr_id_list, $order_detail->goods_num,$goods);
        }
        
        // 用户积分恢复
        $integral = json_decode($order->integral)->forehead_integral;
        $user = User::where(['id' => $order->user_id])->first();
        if ($integral > 0) {
            $user->integral += $integral;
        }
        //余额支付 退回余额
        if ($order->order_status == 1 && $order->pay_type == 1) {
            $user->money += floatval($order->pay_price);
            $data['user_id'] = $user->id;
            $data['operate'] = 3;//退回
            $data['type'] = 1;//余额
            $data['amount'] = $order->pay_price;
            $data['description'] = '取消订单退回余额';
            UserCapitalLog::saveLog($data);
        }
        if (!$user->save()) {
            DB::rollBack();
            throw new \Exception("取消失败，请稍后重试");
        }

        //已付款就退款
        if ($order->order_status == 1 && $order->pay_type == 0) {
            if ($order->pay_price > 0) {
                $refund_res = OrderRefund::refund($order,$order->order_no,$order->pay_price);
                if ($refund_res !== true) {
                    DB::rollBack();
                    return $refund_res;
                }
            }
        }

        if ($order->save()) {
            if ($order->order_status == 4) {
                $user_coupon = UserCoupon::where('user_coupon_id',$order->user_coupon_id)->get();
                foreach($user_coupon as $key => &$v){
                    $v->is_use = 0;
                    $v->save();
                }
            }

            DB::commit();
            return true;
        } else {
            DB::rollBack();
            throw new \Exception("订单取消失败");
        }
    }

    /**
     * 确认收货
     * @return
     */
    public function confirm()
    {
        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");
        $order_id = $this->request->input('order_id');

        $order = Order::where([
            ['user_id','=', $user_id],
            ['id','=', $order_id],
            ['order_status' ,'=', 2],
            ['is_delete' ,'=', 0],
            ['is_recycle' ,'=', 0],
        ])->first();
        if (!$order) {
            throw new \Exception("订单不存在");
        }
        $order->order_status = 3;
        $order->confirm_time = date("Y-m-d H:i:s");
        if ($order->pay_type == 2) {
            $order->order_status = 3;
            $order->pay_time = date("Y-m-d H:i:s");
        }

        if ($order->save()) {
            //发放佣金
            $this->share_money($order->id);
            return true;
        } else {
            throw new \Exception("确认收货失败");
        }
    }

    /**
     * @param $id
     * 佣金发放
     */
    private function share_money($id)
    {
        $share_setting = ShareSetting::first();
        $order = Order::find($id);
        /*
        if ($order->mch_id > 0) {
            $mchPlugin = MchPlugin::findOne(['mch_id' => $order->mch_id, 'store_id' => $this->store_id]);
            if(!$mchPlugin || $mchPlugin->is_share == 0){
                return ;
            }
            $mchSetting = MchSetting::findOne(['mch_id' => $order->mch_id, 'store_id' => $this->store_id]);
            if (!$mchSetting || $mchSetting->is_share == 0) {
                return;
            }
        }
        */
        if ($share_setting->level == 0) {
            return;
        }
        if ($order->is_price != 0) {
            return;
        }
        //分销商自购返利
        $order->share_price = 0;
        if ($order->rebate > 0) {
            $share_user = ShareUser::where('user_id',$order->user_id)->first();
            $share_user->total_price += doubleval($order->rebate);
            $share_user->price += doubleval($order->rebate);
            $share_user->save();
            $order->is_price = 1;
            $order->share_price += doubleval($order->rebate);
            $share_log = ShareLog::where([['user_id','=',$order->user_id],['share_status','=',0]])->first();
            if($share_log){
                $share_log->share_status = 1;
                $share_log->save();
            }
            //ShareLog::set($order->user_id, $order->id, $order->user_id, 20, 0, $order->pay_price, $order->rebate, 1,0,'自购返利');
        }
        //仅自购
        if ($share_setting->level == 4) {
            $order->save();
            return;
        }
        //一级佣金发放
        if ($share_setting->level >= 1) {
            $user_1 = ShareUser::where('user_id',$order->parent_id_1)->first();
            if (!$user_1) {
                return;
            }
            $user_1->total_price += $order->first_price;
            $user_1->price += $order->first_price;
            $user_1->save();
            $share_log = ShareLog::where([['user_id','=',$order->parent_id_1],['share_status','=',0]])->first();
            if($share_log){
                $share_log->share_status = 1;
                $share_log->save();
            }
            //ShareLog::set($user_1->user_id, $order->id, $order->user_id, 10, 10, $order->pay_price, $order->first_price, 1,1,'一级佣金');
            $order->is_price = 1;
            $order->share_price += doubleval($order->first_price);
        }
        //二级佣金发放
        if ($share_setting->level >= 2) {
            $user_2 = ShareUser::where('user_id',$order->parent_id_2)->first();
            if (!$user_2) {
                return;
            }
            $user_2->total_price += $order->second_price;
            $user_2->price += $order->second_price;
            $user_2->save();
            $share_log = ShareLog::where([['user_id','=',$order->parent_id_2],['share_status','=',0]])->first();
            if($share_log){
                $share_log->share_status = 1;
                $share_log->save();
            }
            //ShareLog::set($user_2->user_id, $order->id, $order->user_id, 10, 20, $order->pay_price, $order->second_price, 1,2,'二级佣金');
            $order->is_price = 1;
            $order->share_price += doubleval($order->second_price);
        }
        
        $order->save();
        return;
    }

    /**
     * 订单详情
     * @return $data
     */
    public function detail()
    {
        $user_id = $this->request->attributes->get('userId');
        if($user_id <= 0) throw new \Exception("用户不存在");
        $order_id = $this->request->input('order_id');

        $order = Order::where([
            ['user_id','=', $user_id],
            ['id','=', $order_id],
            ['is_delete' ,'=', 0],
            ['is_recycle' ,'=', 0],
        ])->first();

        if (!$order) {
            throw new \Exception("订单不存在");
        }
        $status = "";
        if ($order->order_status == 0) {
            $status = '订单未付款';
        } elseif ($order->order_status == 1) {
            $status = '订单待发货';
        } elseif ($order->order_status == 2) {
            $status = '订单已发货';
        } elseif ($order->order_status == 3) {
            $status = '订单已完成';
        } elseif ($order->is_cancel == 4) {
            $status = '订单已取消';
        }

        $goods_list = OrderDetail::where([['order_id' ,'=', $order->id], ['is_delete' ,'=', 0]])->get()->toArray();
        $num = 0;
        foreach ($goods_list as $i => $item) {
            $newItem = [];
            $newItem['goods_id'] = $item['goods_id'];
            $newItem['order_detail_id'] = $item['id'];
            $newItem['name'] = $item['goods_name'];
            $newItem['total_price'] = $item['goods_price'];
            $newItem['num'] = $item['goods_num'];
            $newItem['attr'] = json_decode($item['goods_attr']);
            $num += intval($item['goods_num']);
            $newItem['goods_pic'] = $item['goods_pic'];
            $order_refund = OrderRefund::where([
                ['order_detail_id' ,'=', $item['id']],
                ['is_delete' ,'=', 0],
            ])->first();
            if ($order_refund) {
                $newItem['is_order_refund'] = 1;
            } else {
                $newItem['is_order_refund'] = 0;
            }
            if ($order->order_status == 2 || $order->order_status == 3 || $order->order_status == 6) {
                $newItem['order_refund_enable'] = 1;
            } else {
                $newItem['order_refund_enable'] = 0;
            }
            if ($order->order_status == 3) {
                $store = MallSetting::first();
                if ((time() - strtotime($order->confirm_time)) > $store->after_sale_time * 86400) { //超过可售后时间
                    $newItem['order_refund_enable'] = 0;
                }
            }
            if($item['is_level'] == 1 && ($order->discount && $order->discount < 10)){
                $newItem['is_level'] = 1;
            }
            $newList[] = $newItem;
        }
        $shop = '';
        if ($order->shop_id) {
            $shop = Shop::find()->select(['name', 'mobile', 'address', 'longitude', 'latitude'])->where('id', $order->shop_id)->first()->toArray();
        }
        if ($order->before_update_price) {
            if ($order->before_update_price < $order->pay_price) {
                $before_update = "加价";
                $money = $order->pay_price - $order->before_update_price;
            } else {
                $before_update = "优惠";
                $money = $order->before_update_price - $order->pay_price;
            }
        } else {
            $before_update = "";
            $money = "";
        }
        if(!$order->integral){
            $order->integral = 0;
        }
        
        $data = [
            'order_id' => $order->id,
            'status' => $status,
            'express' => $order->express,
            'express_no' => $order->express_no,
            'name' => $order->name,
            'mobile' => $order->mobile,
            'address' => $order->address,
            'order_no' => $order->order_no,
            'addtime' => $order->created_at,
            'total_price' => doubleval(sprintf('%.2f', $order->total_price)),
            'express_price' => doubleval(sprintf('%.2f', $order->express_price)),
            'goods_total_price' => doubleval(sprintf('%.2f', doubleval($order->total_price) - doubleval($order->express_price))),
            'coupon_sub_price' => $order->coupon_sub_price,
            'pay_price' => $order->pay_price,
            'num' => $num,
            'goods_list' => $newList,
            'is_offline' => $order->is_offline,
            'content' => $order->remark ? $order->remark : "",
            'before_update' => $before_update,
            'money' => $money,
            'shop' => $shop,
            'discount' => $order->discount,
            'user_coupon_id' => $order->user_coupon_id,
            'words' => $order->words,
            'pay_type' => $order->pay_type,
            'integral'=> json_decode($order->integral,true),
            //'express_detail' => $express_detail
        ];
        
        return $data;
    }

    /**
     * 获取物流详情
     * @param type express100-快递100 expressbird-快递鸟
     */
    public function getExpressDetail()
    {
        $order_id = $this->request->input('order_id');
        $type = $this->request->input('express_type','expressbird');

        $order = Order::where('id' , $order_id)->first();

        if (!$order) {
            throw new \Exception("订单不存在");
        }
        $status_map = [
            0 => '暂无轨迹信息',
            1 => '已揽收',
            2 => '在途中',
            3 => '已签收',
            4 => '问题件',
        ];
        $store = MallSetting::first();
        $express = new Express($store->kdniao_mch_id,$store->kdniao_api_key,$type); 
        if($type == 'expressbird'){
            $additional=['order_code'=>$order->order_no];
        }else if($type == 'express100'){
            $additional=['phone'=>$order->mobile];
        }
        
        $info = $express->track($order->express_no, $order->express_code, $additional);//快递单号 物流公司编号 额外参数
        
        $info = json_decode($info,true);
        
        $info['express'] = $order->express;
        $info['express_no'] = $order->express_no;
        $od = OrderDetail::where([['order_id' ,'=', $order->id],['is_delete' ,'=', 0]])->first();
        if ($od) {
            $info['goods_pic'] = $od->goods_pic;
        } else {
            $info['goods_pic'] = '';
        }
        
        $info['status_text'] =  $status_map[$info['State']];
        
        return $info;
    }
    
}